#coding=utf-8
from celery import Celery

from django.core.mail import send_mail

from django.conf import settings

from goods.models import GoodsCategory,IndexGoodsBanner,IndexPromotionBanner,IndexCategoryGoodsBanner

from django.template import loader

import os
'''创建celery客户端'''

app = Celery('celery_tasks.tasks', broker='redis://192.168.58.128:6379/4')

@app.task
def send_active_email(to_email, user_name, token):
    """发送激活邮件"""

    subject = "天天生鲜用户激活"  # 标题
    body = ""  # 文本邮件体
    sender = settings.EMAIL_FROM  # 发件人
    receiver = [to_email]  # 接收人
    html_body = '<h1>尊敬的用户 %s, 感谢您注册天天生鲜！</h1>' \
              '<br/><p>请点击此链接激活您的帐号<a href="http://127.0.0.1:8000/users/active/%s">' \
              'http://127.0.0.1:8000/users/active/%s</a></p>' % (user_name, token, token)
    send_mail(subject, body, sender, receiver, html_message=html_body)




'''生成静态的html页面'''
@app.task
def generate_static_index_html():
    # 查询商品分类信息
    categorys = GoodsCategory.objects.all()

    # 查询图片轮播信息，默认index从小到大
    goods_banners = IndexGoodsBanner.objects.all().order_by('index')

    # 查询促销活动信息，默认index从小到大排许
    promotion_banners = IndexPromotionBanner.objects.all().order_by('index')

    # 查询商品分类列表信息
    for category in categorys:
        '''以图片展示的商品'''
        image_banners = IndexCategoryGoodsBanner.objects.filter(category=category, display_type=1)
        category.image_banners = image_banners

        '''以标题展示的商品'''
        title_banners = IndexCategoryGoodsBanner.objects.filter(category=category, display_type=0)
        category.title_banners = title_banners

    cart_num = 20

    context = {

        'categorys': categorys,
        'goods_banners': goods_banners,
        'promotion_banners': promotion_banners,
        # 'title_list': title_list,
        # 'image_list': image_list
        'cart_num': cart_num

    }

    # return render(request, 'index.html', context)
    # 生成的静态html文件，不需要返回render()，只需要一个html即可

    '''加载模板'''#调用模板的常规写法
    template = loader.get_template('static_index.html')

    # 使用上下文渲染模板
    html_data = template.render(context)

    # 放在静态服务器存储/放在celery服务器存储
    # 分析:这个异步任务是被celery服务器阅读的.所以生成的html_data需要存储在celry服务器的某个路径下,管理静态文件的路径下
    '''保存成html文件：放在静态文件中'''
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')

    with open(file_path, 'w') as file:

        file.write(html_data)














